package cn.yunlang.zhangZhongFei.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import cn.yunlang.zhangZhongFei.entity.Goods;
import cn.yunlang.zhangZhongFei.service.GoodsService;
import cn.yunlang.zhangZhongFei.util.JwtUtil;
import cn.yunlang.zhangZhongFei.vo.request.CompanyVo;
import cn.yunlang.zhangZhongFei.vo.response.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import javax.annotation.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/Goods")
@Api(tags = "商品")
public class GoodsController {

  @Resource private GoodsService goodsService;

  @ApiOperation(value = "分页查询商品", notes = "支持按发布者和公司名称搜索，结果按创建时间倒序排序")
  @GetMapping("/page")
  public R<IPage<Goods>> page(
      @ApiParam(value = "页码", required = true, example = "1") @RequestParam(defaultValue = "1")
          Integer pageNo,
      @ApiParam(value = "每页记录数", required = true, example = "10") @RequestParam(defaultValue = "10")
          Integer pageSize,
      @ApiParam(value = "发布者ID，不传则查询所有") @RequestParam(required = false) Long publisherId,
      @ApiParam(value = "公司名称，支持模糊搜索") @RequestParam(required = false) String companyName) {
    // 参数校验和默认值处理
    pageNo = Math.max(1, pageNo);
    pageSize = Math.min(100, Math.max(1, pageSize)); // 限制每页最大100条

    // 获取当前用户ID
    Long userId = Long.valueOf(new JwtUtil().getUserId());
    if (userId == null) {
      return R.error(401, "用户未登录");
    }

    // 执行分页查询
    return goodsService.getPage(new Page<>(pageNo, pageSize), userId, publisherId, companyName);
  }

  @GetMapping("/one")
  @ApiOperation("根据Id查一条  内容")
  public R<Goods> one(@RequestParam Long goodsId) {
    return goodsService.getOne(goodsId);
  }

  @PostMapping("/add")
  @ApiOperation("新增")
  public R<String> add(@RequestBody CompanyVo companyVo) {
    return goodsService.addNew(companyVo);
  }

  @GetMapping("/delete")
  @ApiOperation("删除")
  public R<String> delete(@RequestParam Long goodsId) {
    return goodsService.deleteGoods(goodsId);
  }

  @PostMapping("/update")
  @ApiOperation("修改")
  public R<String> update(@RequestBody Goods goods) {
    return goodsService.updateGoods(goods, new JwtUtil().getUserId());
  }
}
